package wox.lonice.btctrade.service.Impl;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wox.lonice.btctrade.common.BaseConstant;
import wox.lonice.btctrade.dto.LinkeEntityDto;
import wox.lonice.btctrade.enums.btcTrade.BtcTradeEnum;
import wox.lonice.btctrade.enums.btcTrade.EthTradeEnum;
import wox.lonice.btctrade.enums.btcTrade.UscTradeEnum;
import wox.lonice.btctrade.exception.CoinAreaException;
import wox.lonice.btctrade.exception.TradeException;
import wox.lonice.btctrade.service.CoinAreaService;
import wox.lonice.btctrade.service.ConsumeService;
import wox.lonice.btctrade.service.TradeService;
import wox.lonice.utis.ObjectUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>描述：实现接口</p>
 *
 * @author LoNice
 * @Date 2018/5/28 10:19
 */
@Service
public class CoinAreaServiceImpl implements CoinAreaService, BaseConstant {
    private Logger logger = LoggerFactory.getLogger(CoinAreaService.class);

    @Autowired
    private TradeService tradeService;

    @Autowired
    private ConsumeService consumeService;

    @Override
    public void btcMiningArea() throws CoinAreaException {
        BtcTradeEnum[] btcTradeEnums =  BtcTradeEnum.values();
        ExecutorService pool = Executors.newFixedThreadPool(threadPoolNum);
        for (final BtcTradeEnum btcEnum : btcTradeEnums){
            pool.submit((Runnable) () -> {
//                System.out.println("[ " + BTC + "区 ]" + btcEnum.toString());
                getOrderPercent(BTCTRADE_DOMAIN, BTC, btcEnum.toString().toLowerCase());
            });
        }
        pool.shutdown();
    }

    @Override
    public void ethMiningArea() throws CoinAreaException {
        EthTradeEnum[] ethTradeEnums = EthTradeEnum.values();
        ExecutorService pool = Executors.newFixedThreadPool(threadPoolNum);
        for (final EthTradeEnum ethEnum : ethTradeEnums){
            pool.submit((Runnable) () -> {
//                System.out.println("[ " + ETH + "区 ]" + ethEnum.toString());
                getOrderPercent(BTCTRADE_DOMAIN, ETH, ethEnum.toString().toLowerCase());
            });
        }
        pool.shutdown();
    }

    @Override
    public void uscMiningArea() throws CoinAreaException {
        UscTradeEnum[] uscTradeEnums =  UscTradeEnum.values();
        ExecutorService pool = Executors.newFixedThreadPool(threadPoolNum);
        for (final UscTradeEnum uscEnum : uscTradeEnums){
            pool.submit((Runnable) () -> {
//                System.out.println("[ " + USC + "区 ]" + uscEnum.toString());
                getOrderPercent(BTCTRADE_DOMAIN, USC, uscEnum.toString().toLowerCase());
            });
        }
        pool.shutdown();
    }

    private void getOrderPercent(String domain, String area, String coin){
        try {
            JSONObject jsonObject = tradeService.order(domain, area, coin);
            if(ObjectUtil.isNotEmpty(jsonObject.getString("f"))){
//                System.out.println(jsonObject.getString("f"));
                BigDecimal percent = jsonObject.getBigDecimal("f");
                if (percent.compareTo(RISE_PERCENT) == 1 || percent.compareTo(FALL_PERCENT) == -1 ){
                    JSONObject ticker = tradeService.ticker(domain, area, coin);
                    String body = "";
                    if("Suceess".equals(ticker.getString("msg"))){
                        JSONObject jsonData = ticker.getJSONObject("data");
                        if(ObjectUtil.isNotEmpty(jsonData)){
//                            //最高价
//                            BigDecimal hight = jsonData.getBigDecimal("high");
//                            //最近一次成交价
//                            BigDecimal last = jsonData.getBigDecimal("last");
//                            //最低价
//                            BigDecimal low = jsonData.getBigDecimal("low");
//                            //买一价
//                            BigDecimal buy = jsonData.getBigDecimal("buy");
//                            //卖一价
//                            BigDecimal sell = jsonData.getBigDecimal("sell");
//                            //成交量
//                            String vol = jsonData.getString("vol");
                            body = "交易区: " + area + ",  币种: " + coin + ",  最高值: " + jsonData.getBigDecimal("high")
                                    + ",  最低值: " + jsonData.getBigDecimal("low")
                                    + ",  最近一次成交价: " + jsonData.getBigDecimal("last")
                                    + ",  买一价: " + jsonData.getBigDecimal("buy")
                                    + ",  卖一价: " + jsonData.getBigDecimal("sell")
                                    + ",  当前涨跌值: " + percent + "%\n";
//                            System.out.println(jsonData);
                            //生产者添加
                            LinkeEntityDto linkeEntityDto = new LinkeEntityDto();
                            linkeEntityDto.setArea(area);
                            linkeEntityDto.setCoin(coin);
                            linkeEntityDto.setBody(body);
                            linkeEntityDto.setDomain(domain);
                            linkeEntityDto.setPercent(percent);
                            linkeEntityDto.setThisDate(new Date().getTime());
                            System.out.println("存入数据: " + linkeEntityDto);
                            LINKED_BLOCKING_DEQUE.add(linkeEntityDto);
                        }
                    }
//                    System.out.println(body);
//                    MailUtil.sendMail("451932185@qq.com", area + "交易区最新行情", body);
                }
            }
        } catch (TradeException e) {
            e.printStackTrace();
        }
    }


    //"0 0 12 * * ?"    每天中午十二点触发
    //"0 15 10 ? * *"    每天早上10：15触发
    //"0 15 10 * * ?"    每天早上10：15触发
    //"0 15 10 * * ? *"    每天早上10：15触发
    //"0 15 10 * * ? 2005"    2005年的每天早上10：15触发
    //"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发
    //"0 0/5 14 * * ?"    每天从下午2点开始到2：55分结束每5分钟一次触发
    //"0 0/5 14,18 * * ?"    每天的下午2点至2：55和6点至6点55分两个时间段内每5分钟一次触发
    //"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发
    //"0 10,44 14 ? 3 WED"    三月的每周三的14：10和14：44触发
    //"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10：15触发
//    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    public void asedw(){
        try {
            btcMiningArea();
            ethMiningArea();
            uscMiningArea();
        } catch (CoinAreaException e) {
            e.printStackTrace();
        }
//        getOrderPercent(BTCTRADE_DOMAIN, BTC, "lxt");
    }

//    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    public void aewssd(){
        consumeService.dealLinkeDto();
    }

    public static void main(String[] args) throws TradeException {
////        JSONObject jsonObject = new TradeServiceImpl().order(BTCTRADE_DOMAIN, ETH, "lxt");
//        JSONObject jsonObject = new TradeServiceImpl().order(COINEGG_DOMAIN, ETH, wox.lonice.btctrade.enums.coinegg.EthTradeEnum.ABTC.toString().toLowerCase());
//        //chg
//        System.out.println(jsonObject);

        LinkeEntityDto linkeEntityDto = new LinkeEntityDto();
        linkeEntityDto.setThisDate(new Date().getTime());
        LINKED_BLOCKING_DEQUE.add(linkeEntityDto);
        linkeEntityDto = new LinkeEntityDto();
        linkeEntityDto.setThisDate(new Date().getTime());
        LINKED_BLOCKING_DEQUE.add(linkeEntityDto);
        System.out.println(LINKED_BLOCKING_DEQUE.size());
        LINKED_BLOCKING_DEQUE.poll();
        System.out.println(LINKED_BLOCKING_DEQUE.size());


    }
}
